// ----------------------- 获取学员数据 -------------------------

function renderStudent() {
  axios.get("/student/list").then(({ data: res }) => {
    // console.log(res);
    if (res.code === 0) {
      // 字符串
      let studentStr = "";
      res.data.forEach((item, index) => {
        studentStr += `
        <tr>
          <th scope="row">${index + 1}</th>
          <td>${item.name}</td>
          <td>${item.age}</td>
          <td>${item.sex}</td>
          <td>${item.phone}</td>
          <td>${item.salary}</td>
          <td>${item.truesalary}</td>
          <td>${item.province}</td>
          <td>${item.province}${item.city}${item.county}</td>
          <td>
            <button type="button" data-id="${
              item.id
            }" class="btn btn-primary btn-sm">修改</button>
            <button type="button" data-id="${
              item.id
            }" class="btn btn-danger btn-sm">删除</button>
          </td>
        </tr>`;
        qs("tbody").innerHTML = studentStr;
      });

      // 数组
      // let arr = [];
      // res.data.forEach((item) => {
      //   arr.push(`
      //     <tr>
      //       <th scope="row">${item.id}</th>
      //       <td>${item.name}</td>
      //       <td>${item.age}</td>
      //       <td>${item.sex}</td>
      //       <td>${item.phone}</td>
      //       <td>${item.salary}</td>
      //       <td>${item.truesalary}</td>
      //       <td>${item.province}</td>
      //       <td>${item.province}${item.city}${item.county}</td>
      //       <td>
      //         <button type="button" class="btn btn-primary btn-sm">修改</button>
      //         <button type="button" class="btn btn-danger btn-sm">删除</button>
      //       </td>
      //     </tr>`);
      // });
      // arr.forEach(() => {
      //   qs("tbody").innerHTML = arr.join("");
      // });
    }
  });
}
renderStudent();
// ----------------------- 添加显示弹层 --------------------------
qs("#addBtn").addEventListener("click", function () {
  qs("#addModal").classList.add("show");
  qs("#backdrop").classList.add("show");
});
qs("#closeAddBtn").addEventListener("click", function () {
  qs("#addModal").classList.remove("show");
  qs("#backdrop").classList.remove("show");
});
// --------------------- 获取省 ---------------------
axios.get("/geo/province").then(({ data: res }) => {
  let strProvince = `<option selected value="">--省--</option>`;
  res.forEach((item) => {
    strProvince += `<option  value="${item}">${item}</option>`;
  });
  qsAll('select[name="province"]').forEach(
    (item) => (item.innerHTML = strProvince)
  );
});
// 直接获取市

// 直接获取县
// --------------------- 省切换的时候，选择市 ---------------------
qsAll('select[name="province"]').forEach((item, index) => {
  item.addEventListener("change", function () {
    qsAll('select[name="county"]')[
      index
    ].innerHTML = `<option selected value="">--县--</option>`;
    let pname = this.value;
    axios
      .get("/geo/city", {
        params: {
          pname,
        },
      })
      .then(({ data: res }) => {
        let cityStr = `<option selected value="">--市--</option>`;
        res.forEach((item) => {
          cityStr += `<option  value="${item}">${item}</option>`;
        });
        qsAll('select[name="city"]')[index].innerHTML = cityStr;
      });
  });
});
// --------------------- 市切换的时候，选择县 ---------------------
qsAll('select[name="city"]').forEach((item, index) => {
  item.addEventListener("change", function () {
    let cname = this.value;
    let pname = qsAll('select[name="province"]')[index].value;
    axios
      .get("/geo/county", {
        params: {
          pname,
          cname,
        },
      })
      .then(({ data: res }) => {
        let countyStr = `<option selected value="">--县--</option>`;
        res.forEach((item) => {
          countyStr += `<option  value="${item}">${item}</option>`;
        });
        qsAll('select[name="county"]')[index].innerHTML = countyStr;
      });
  });
});
// -------------------- 添加完成 ----------------------------------
qs(".add-form").addEventListener("submit", function (e) {
  e.preventDefault();
  const formObj = getForm(".add-form");
  axios.post("/student/add", formObj).then(({ data: res }) => {
    if (res.code === 0) {
      alert(res.message);
      qs("#closeAddBtn").click();
      renderStudent();
    }
  });
});
// ----------------------- 修改显示弹层 --------------------------
// 修改学员 / 删除学员(事件委托)
qs("tbody").addEventListener("click", function (e) {
  let id = e.target.dataset.id;
  if (e.target.innerHTML === "修改") {
    axios
      .get("/student/one", {
        params: {
          id,
        },
      })
      .then(({ data: res }) => {
        // console.log(res);
        if (res.code === 0) {
          const {
            name,
            age,
            city,
            county,
            group,
            phone,
            province,
            salary,
            sex,
            truesalary,
            id,
          } = res.data;
          qs('#updateModal input[type="hidden"]').value = id;
          qs('#updateModal input[name="name"]').value = name;
          qs('#updateModal input[name="age"]').value = age;
          qs('#updateModal input[name="phone"]').value = phone;
          qs('#updateModal input[name="salary"]').value = salary;
          qs('#updateModal input[name="truesalary"]').value = truesalary;
          qs(`#updateModal input[name="sex"][value="${sex}"]`).checked = true;
          qs(`#updateModal select[name="group"]`).value = group;
          qs(`#updateModal select[name="province"]`).value = province;
          qs(
            `#updateModal select[name="city"] `
          ).innerHTML = `<option selected value="${city}">${city}</option>`;
          qs(
            `#updateModal select[name="county"]`
          ).innerHTML = `<option selected value="${county}">${county}</option>`;
          qs("#updateModal").classList.add("show");
          qs("#backdrop").classList.add("show");
        }
      });
  }
});
qs("#closeUpdateBtn").addEventListener("click", function () {
  qs("#updateModal").classList.remove("show");
  qs("#backdrop").classList.remove("show");
});

// ------------------------- 修改学员 - 确认修改 ----------------------------
qs(".update-form").addEventListener("submit", function (e) {
  e.preventDefault();
  const formObj = getForm(".update-form");
  axios.put("/student/update", formObj).then(({ data: res }) => {
    if (res.code === 0) {
      alert(res.message);
      qs("#closeUpdateBtn").click();
      renderStudent();
    }
  });
});
// 删除功能
qs("tbody").addEventListener("click", function (e) {
  let id = e.target.dataset.id;
  if (!confirm("Are you sure?")) return;
  if (e.target.innerHTML === "删除") {
    axios
      .delete("/student/delete", {
        params: { id },
      })
      .then(({ data: res }) => {
        if (res.code === 0) {
          renderStudent();
        }
      });
  }
});
